/**
 * Created by zhouli on 18/2/7
 * Email li.zhou@huilianyi.com
 * 扩展字段组件需要被复用，成本中心扩展字段也需要用
 * 凡是需要用到扩展字段配置的地方
 */
import React from 'react';
import {connect} from 'react-redux';
import EFService from 'containers/enterprise-manage/extend-field/extend-field.service';
import 'styles/enterprise-manage/extend-field/extend-field.scss';
import ExtendFieldComponent from 'components/template/extend-field-setting/extend-field';
import {messages} from "share/common";
import BaseService from 'share/base.service';
import menuRoute from 'routes/menuRoute';

import {
  message
} from 'antd';
//默认的扩展字段表单，Profile中没有获取到，就使用这个
const extendFieldDefault = {
  "formName": "用户附加信息",//用户附加信息
  "iconName": "user_attach_info",
  "messageKey": "user_attach_form",
  "formType": 5001,
  "formCode": "user_attach_form",
  "asSystem": false,
  "valid": true,
  "parentOID": null,
  "associateExpenseReport": false,
  "customFormFields": [],
  "remark": "人员附加信息",//
  "referenceOID": null,
  "visibleExpenseTypeScope": 1001,
  "visibleUserScope": 1001
};
//待添加的字段类型
let customFromOriginList = [];
//待添加的字段类型，常用的字段类型
let customFromOriginListWithOften = [];
//常用扩展字段类型名称
let customFromOriginListWithOftenName = [];
//租户级别值列表
let allEnumerationsList = [];

class ExtendField extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      customFromOriginList: [],//可以选择表单类型
      customFrom: {},//配置的表单
    }
  }
  componentDidMount() {
    this.getWidgetList();
  }

  // 获取表单字段类型
  getWidgetList = () => {
    //发送三个请求
    EFService.getWidgetListAll()
      .then(res => {
        this.getViewDataForExtendFiled();
      })
  };

  //直接获取到两个列表，与一个值列表
  getViewDataForExtendFiled = () => {
    EFService.getViewDataForExtendFiled()
      .then(res => {
        allEnumerationsList = res.allEnumerationsList;
        customFromOriginList = res.customFromOriginList;
        customFromOriginListWithOften = res.customFromOriginListWithOften;
        customFromOriginListWithOftenName = res.customFromOriginListWithOftenName;
        customFromOriginListWithOften.map(item => {
          if (item.fieldCode === 'heliosspc_remark_control') {
            let target = this.getDefaultEnumeration(item, allEnumerationsList);
            item.dataSource = target ? JSON.stringify({"customEnumerationOID": target.customEnumerationOID}) : "";
          }
          item._showName = this.getShowNameByKey(item.messageKey, customFromOriginListWithOftenName);
        })
        this.getCustomForm();
      })
  }

  //获取用车必填控制，默认值列表
  getDefaultEnumeration = (defaultItem, list) => {
    let target = null;
    list.map(item => {
      if ((defaultItem.defaultValue + "") === (item.systemCustomEnumerationType + "")) {
        target = item;
      }
    });
    return target;
  };

  //根据值列表，获取常用扩展字段应该显示的类型名称
  getShowNameByKey = (key, customFromOriginListWithOftenName) => {
    let t = null;
    customFromOriginListWithOftenName.map(item => {
      if (key === item.value) {
        t = item.messageKey;
      }
    });
    return t;
  };

  setCustomFormFieldI18nDTOS = (originCustomFormFields) => {
    let nowWidget = originCustomFormFields;
    //counterFlag为内部组件排序所需key值，在此处初始化
    nowWidget.map((widget, index) => {
      //添加一个 fieldCodeForDisabled 主要用来实现有编码不能编辑的功能
      widget.fieldCodeForDisabled = widget.fieldCode;
      //联动开关要用
      if (!widget.customFormFieldI18nDTOS || widget.customFormFieldI18nDTOS.length === 0) {
        widget.customFormFieldI18nDTOS = [];
        this.props.languageList.map(language => {
          let i18nDTO = {
            fieldName: widget.fieldName,
            promptInfo: widget.promptInfo,
            language: language.code
          };
          widget.customFormFieldI18nDTOS.push(i18nDTO);
        });
      }

      if (!widget.i18n) {
        widget.i18n = {};
      }
      if (!widget.i18n.fieldName || !widget.i18n.fieldName.length) {
        let fieldNameI18n = [];
        this.props.languageList.map(language => {
          let i18nDTO = {
            language: language.code,
            value: widget.fieldName ? widget.fieldName : ''
          };
          fieldNameI18n.push(i18nDTO);
        });
        widget.i18n.fieldName = fieldNameI18n;
      }

      if (!widget.i18n.promptInfo || !widget.i18n.promptInfo.length) {
        let promptInfoI18n = [];
        this.props.languageList.map(language => {
          let i18nDTO = {
            language: language.code,
            value: widget.promptInfo ? widget.promptInfo : ''
          };
          promptInfoI18n.push(i18nDTO);
        });
        widget.i18n.promptInfo = promptInfoI18n;
      }
      return widget;
    });
  }
  // 获取表单
  getCustomForm = () => {
    // 如果没有需要前端初始化创建
    if (this.props.profile["_self.company.contact.custom.form"]) {
      this.setState({
        loading: true
      });
      EFService.getCustomForm(this.props.profile["_self.company.contact.custom.form"])
        .then((res) => {
          if (res.data === "" || res.data === undefined || res.data === null) {
            //没有获取到表单
            message.warn(messages('enterprise-manage.key57'/*没有获取到表单*/));
            return;
          }
          let customFrom = res.data;
          if (customFrom.customFormFields && customFrom.customFormFields.length > 0) {
            this.setCustomFormFieldI18nDTOS(customFrom.customFormFields);
          }
          if (customFrom.customFormFields && customFrom.customFormFields.length > 0) {
            customFrom.customFormFields[0]._active = true;
          }
          this.setState({
            loading: false,
            customFrom,
            customFromOriginList,
            customFromOriginListWithOften
          })
        })
    } else {
      this.setState({
        customFrom: extendFieldDefault,
        customFromOriginList,
        customFromOriginListWithOften
      })
    }
  };
  // 创建更新入口
  createOrUpdate = (form) => {
    if (this.props.profile["_self.company.contact.custom.form"]) {
      this.updateCustomForm(form)
    } else {
      this.createCustomForm(form)
    }
  };
  // 创建表单
  createCustomForm = (form) => {
    this.setState({
      loading: true,
    });
    EFService.createCustomForm(form)
      .then((res) => {
        message.success(messages('enterprise-manage.key58'/*更新成功*/));
        this.setState({
          loading: false,
        });
        // 需要重新获取表单
        this.getCustomForm();
        // 这个地方需要更新一下functionProfile，因为创建表单之后，接口数据变化了
        BaseService.getProfile();
      })
  };
  // 更新表单
  updateCustomForm = (form) => {
    if (!form.formOID) {
      //只有当新增之后，立即再次更新执行这个逻辑
      form.formOID = this.props.profile["_self.company.contact.custom.form"]
    }
    this.setState({
      loading: true,
    });
    EFService.updateCustomForm(form)
      .then((res) => {
        message.success(messages('enterprise-manage.key58'/*更新成功*/));
        // 需要重新获取表单
        this.getCustomForm();
        this.setState({
          loading: false,
        })
      })
  };
  // 取消
  cancel = () => {
    this.context.router.push(menuRoute.getRouteItem('person-manage').url);
  };

  // 获取扩展字段表单
  render() {
    const {loading, customFrom, customFromOriginList} = this.state;
    const {tenantMode} = this.props;
    return (
      <div className="extend-field-wrap">
        <ExtendFieldComponent
          showOftenField={true}
          loading={loading}
          filedMax={10}
          cancel={this.cancel}
          rightIsShow={tenantMode}
          bottomBtnIsShow={tenantMode}
          leftDragable={tenantMode}
          saveFrom={this.createOrUpdate}
          customFrom={customFrom}
          customFromOriginListWithOften={customFromOriginListWithOften}
          customFromOriginList={customFromOriginList}
        />
      </div>
    )
  }
}

ExtendField.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    language: state.main.language,
    languageList: state.login.languageList,
  }
}

export default connect(mapStateToProps)(ExtendField);
